#include "AmperSensor.h"

#include "ADConvert.h"
#include "VBattery.h"

struct _AmperSensor
{
        ADChannelType base_type;
#ifdef VBATTERY_H
        VBattery *vbattery;
#endif
};

static AmperSensor global_amper_sensor;

static float       amper_adjust = 0.0f;

AmperSensor *
amper_sensor_new_from_global(void)
{
        adconvert_init();
        global_amper_sensor.base_type = ADCHANNEL_TYPE_AMPER;

        /* 自动校准 */
        const uint16_t _amper = adconvert_get_value_once(ADCHANNEL_TYPE_AMPER);
        amper_adjust          = (float)_amper * 0.01221f;
#ifdef VBATTERY_H
        global_amper_sensor.vbattery = vbattery_new_from_global();
#endif
        return &global_amper_sensor;
}

float
amper_sensor_get_amper(const AmperSensor *self)
{
#ifndef VBATTERY_H
        const uint16_t amper = adconvert_get_value_once(self->base_type);
        return (float)amper * 0.01221f - amper_adjust;
#else
        return vbattery_get_amper(self->vbattery);
#endif
}
